package address

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserAddressByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 通过ID获取UserAddress
func NewGetUserAddressByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserAddressByIdLogic {
	return &GetUserAddressByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUserAddressByIdLogic) GetUserAddressById(
	req *types.IDReq,
	headers *[]*types.Header,
) (resp *types.UserAddressInfo, err error) {
	if req.Id == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_ID_REQUIRED)
	}

	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	preload := "userAddress:Id,UserId,Consignee,Mobile,Province,City,District,DetailedAddress,PostalCode,IsDefault,Status,meta"
	// 构造查询条件
	var filters []string
	filters = append(filters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	data, err := l.svcCtx.UserRpc.GetUserAddressById(l.ctx, &userclient.BaseIdReq{
		Id:         pointy.GetPointer(req.Id),
		Preload:    pointy.GetPointer(preload),
		Filter:     pointy.GetPointer(strings.Join(filters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		return nil, err
	}

	if data == nil || data.Id == nil || *data.Id == 0 {
		return nil, resultx.NewErrCode(resultx.USER_ADDRESS_ID_INVALID)
	}

	var geographic []*types.MetaInfo
	if len(data.Geographic) > 0 {
		for _, v := range data.Geographic {
			geographic = append(geographic, &types.MetaInfo{
				Key:   v.Key,
				Label: v.Label,
				Value: v.Value,
			})
		}
	}

	return &types.UserAddressInfo{
		Id:              data.Id,
		Label:           data.Label,
		Consignee:       data.Consignee,
		Mobile:          data.Mobile,
		Province:        data.Province,
		City:            data.City,
		District:        data.District,
		Street:          data.Street,
		DetailedAddress: data.DetailedAddress,
		PostalCode:      data.PostalCode,
		RegionCode:      data.RegionCode,
		IsDefault:       data.IsDefault,
		Geographic:      geographic,
	}, nil
}
